﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using DHM.WXMiniProgram.Utility._MD5;
using DHM.WXMiniProgram.Utility.APIResult;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

namespace DHM.WXMiniProgram.Controllers
{
    public class TokenOption
    {
        public string Issure { get; set; }
        public string Audience { get; set; }

        public string Scecret  { get; set; }

        public string Expiration { get; set; }

        public int  RefreshJwtTime { get; set; }
    }
    [Route("api/[controller]")]
    [ApiController]
    public class AuthorizeController : ControllerBase
    {


        private readonly IConfiguration _configuration;
        public AuthorizeController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        [HttpPost("Login")]
        public  APIResult Login([FromForm]string username,[FromForm]string password)
        {
            //var username = user.UserName;
            //var password = user.Password;

            var localUser = _configuration["User:username"];
            var localPwd = _configuration["User:password"];

            if (username == "" || password == "") return APIResultHelper.Error("无权访问");

            if (!localUser.Equals(username)) return APIResultHelper.Warning("无权访问", 401);

            string localhash = MD5Helper.MD5Encrypt32(localPwd);
            string remotehash = MD5Helper.MD5Encrypt32(password);

            if (!localhash.Equals(remotehash)) return APIResultHelper.Warning("无权访问", 401);

            if (username.Equals(localUser) && localhash.Equals(remotehash))
            {
                var claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name,localUser),
                    new Claim(ClaimTypes.Uri,Request.GetDisplayUrl())

                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT_Secretkey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                JwtSecurityToken jwt = new JwtSecurityToken(
                    claims: claims,
                    notBefore: DateTime.Now,
                    expires: DateTime.Now.AddHours(24),
                    signingCredentials: creds
                );

                var tokens = new JwtSecurityTokenHandler().WriteToken(jwt);

                return APIResultHelper.Success(new
                {
                    token = tokens
                });
            }
            else
            {
                return APIResultHelper.Warning("无权访问", 401);
            }
        }
    }
}
